<template>
  <view class="wrapper">
    <u-popup
      v-model="showPopup"
      border-radius="20"
      :safe-area-inset-bottom="true"
      mode="bottom"
      :mask-custom-style="{ background: 'rgba(0, 0, 0, 0.7)' }"
    >
      <view class="part-popup">
        <u-tabs
          bg-color="transparent"
          :list="subList"
          v-model="subCurrent"
          :is-scroll="false"
          :duration="0.2"
          font-size="28"
          height="100"
          @change="handleSubChange"
        />
        <view class="tabs-line"></view>
        <scroll-view :scroll-y="true" class="content-scroll">
          <view class="tips-box" v-if="subCurrent !== 0">
            <view class="icon">i</view>
            <view class="text">退差价的退单将不核销ERP，请酌情处理</view>
          </view>
          <view class="goods-list">
            <view class="goods-item" v-for="(goods, index) in goodsList" :key="index">
              <view class="item-flex">
                <view class="item-radio">
                  <view
                    @click="handleCheckItem(goods, index)"
                    v-if="((goods.refundStatus !== RefundStatusEnum.NEW.value && goods.refundStatus !== RefundStatusEnum.REFUNDED.value)
                      || goods.quantity > (goods.totalRefundQuantity || 0))"
                  >
                    <u-checkbox class="checkbox" shape="circle" :modelValue="goods.checked" :activeColor="appTheme.mainBg" />
                  </view>
                </view>
                <view class="image-wrap">
                  <image :src="goods.primaryPicUrl" />
                </view>
                <view class="good-info">
                  <view class="title-wrap">
                    <text class="name oneline-hide">{{goods.goodsName}}</text>
                    <text>¥ {{ goods.sellPrice || goods.originalPrice }}</text>
                  </view>
                  <view class="describe">编码： {{ goods.skuCode }}</view>
                  <view class="describe">条码：{{ goods.barcode }}</view>
                  <view class="describe">
                    <text>重量：{{ goods.weight || 0 }}g</text>
                    <text>x {{goods.quantity}}</text>
                  </view>
                  <view
                    class="goods-tips"
                    v-if="(goods.refundStatus === RefundStatusEnum.NEW.value || goods.refundStatus === RefundStatusEnum.REFUNDED.value)
                      && goods.totalRefundQuantity"
                  >
                    <text class="tips-icon">!</text>
                    <text class="tips-text">{{ goods.refundStatus === 1 ? '退货申请中' : '已退货' }}</text>
                    <text class="tips-refund-text">共退：{{ goods.totalRefundQuantity }}件</text>
                    <text class="tips-top"/>
                  </view>
                </view>
              </view>
              <view class="stepper" v-if="goods.checked && subCurrent === 0">
                <text class="m-r-10">退款数量</text>
                <u-number-box
                  v-model="goods.number"
                  :max="(goods.quantity - goods.refundQuantity) || 0"
                  buttonSize="15"
                ></u-number-box>
              </view>
              <view class="stepper" v-if="goods.checked
                  && (((channelId === ChannelTypeEnum.ELE.value
                  || channelId === ChannelTypeEnum.APPLET.value
                  || channelId === ChannelTypeEnum.DY.value) && subCurrent === 1)
                  || ((channelId === ChannelTypeEnum.MT.value) && subCurrent === 2))">
                <text>退款金额</text>
                <u-input
                  v-model="goods.customRefundAmount"
                  type="digit"
                  placeholder="请输入金额"
                  height="36"
                  :custom-style="customStyle"
                />
                <text>元，</text>
                <text>剩余可退：¥ {{ goods.remainingRefundAmount || (goods.sellAmount - goods.refundAmount).toFixed(2) }}</text>
              </view>
              <view v-if="goods.checked && (channelId === ChannelTypeEnum.JD.value || channelId === ChannelTypeEnum.MT.value) && subCurrent === 1">
                <view class="stepper weight" v-for="(wItem, wIndex) in goods.actualWeights" :key="wIndex">
                  <text>{{wIndex + 1}} <text class="m-l-10">应拣重量：{{goods.weight}}</text>g</text>
                  <text class="m-l-10">实拣重量：</text>
                  <u-input
                    v-model="wItem.weight"
                    type="digit"
                    placeholder="请输入实拣重量"
                    height="36"
                    :custom-style="customStyle"
                  />
                  <text>g</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="footer-fixed">
          <view class="btn-wrapper">
            <u-button :custom-style="{width: '330rpx'}" @click="showPopup = false">取消</u-button>
            <u-button :custom-style="{width: '330rpx'}" type="primary" @click="handlePartReturn">提交</u-button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import ChannelTypeEnum from "@/common/enum/channelType"
import OrderStatusEnum from "@/common/enum/order/orderStatus"
import RefundStatusEnum from "@/common/enum/order/refundStatus"

export default {
  name: "index",
  props: {
    order: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      ChannelTypeEnum,
      OrderStatusEnum,
      RefundStatusEnum,
      showPopup: false,
      subList: [{name: '按件数退'}, {name: '按金额退'}],
      subCurrent: 0,
      goodsList: [],
      customStyle: {
        backgroundColor: '#f5f7fa',
        borderRadius: '8rpx',
        width: '120rpx',
        fontSize: '24rpx',
        textAlign: 'center',
        margin: '0 10rpx'
      }
    }
  },
  computed: {
    channelId() {
      return this.order.thirdChannelId
    }
  },
  methods: {
    show() {
      const {orderGoods, goodsList, thirdChannelId, orderStatus} = this.order
      switch (thirdChannelId) {
        case ChannelTypeEnum.ELE.value:
        case ChannelTypeEnum.APPLET.value:
        case ChannelTypeEnum.DY.value:
          this.subList = [{name: '按件数退'}, {name: '按金额退'}]
          break
        case ChannelTypeEnum.JD.value:
          this.subList = [{name: '按件数退'}, {name: '按重量退'}]
          break
        case ChannelTypeEnum.MT.value:
          // 美团渠道订单已完成才可按金额退
          this.subList = orderStatus === OrderStatusEnum.COMPLETED.value ? [{name: '按件数退'}, {name: '按重量退'}, {name: '按金额退'}] : [{name: '按件数退'}, {name: '按重量退'}]
          break
        default:
          this.subList = [{name: '按件数退'}]
      }
      this.goodsList = orderGoods || goodsList
      this.handleGoodsFactory()
      this.showPopup = true
    },
    hide() {
      this.showPopup = false
    },
    handleGoodsFactory() {
      for(let i = 0; i < this.goodsList?.length; i++) {
        let item = this.goodsList[i]
        item.number = 1
        item.checked = false
        item.customRefundAmount = 0
        item.actualWeights = []
        for (let j = 0; j < item.quantity; j++) {
          let obj = {weight: 0}
          item.actualWeights.push(obj)
        }
      }
    },
    handleSubChange(index) {
      this.subCurrent = index
      this.handleGoodsFactory()
    },
    handleCheckItem(item, index) {
      let {checked} = item
      this.$set(this.goodsList[index], 'checked', !checked)
      this.$forceUpdate()
    },
    handlePartReturn() {
      const isSome = this.goodsList.some(item => item.checked)
      if (!isSome) return this.$toast('请选择商品!')
      // 是否整单退
      let isRefundAll = false
      // 按件数退时进行数量统计
      if (this.subCurrent === 0) {
        // 按件数退选中的总数量
        let selectCount = 0
        // 按件数退商品的总数量
        let goodsCount = 0
        this.goodsList.forEach(goods => {
          let { quantity, totalRefundQuantity, number, checked } = goods
          goodsCount += quantity
          if (!checked) {
            number = 0
          }
          selectCount = (totalRefundQuantity || 0) + (number || 0) + selectCount
        })
        isRefundAll = selectCount >= goodsCount
      }

      let selectedArr = this.goodsList.filter(val => val.checked)
      for(let i = 0; i < selectedArr.length; i++) {
        const item = selectedArr[i]
        item.weights = []
        if (this.subCurrent === 0) {
          if (!item.number) {
            return this.$toast('请输入退款数量!')
          }
        }
        if (((this.channelId === ChannelTypeEnum.ELE.value
            || this.channelId === ChannelTypeEnum.APPLET.value
            || this.channelId === ChannelTypeEnum.DY.value) && this.subCurrent === 1)
          || ((this.channelId === ChannelTypeEnum.MT.value) && this.subCurrent === 2)) {
          if (Number(item.customRefundAmount) === 0 || !item.customRefundAmount) {
            return this.$toast(`请输入第${i+1}件商品退款金额!`)
          }
          if (item.customRefundAmount < 0) {
            return this.$toast(`金额必须大于0，请修改第${i+1}件的退款金额!`)
          }
          const reg = /^\d+(\.\d{1,2})?$/
          if (!reg.test(item.customRefundAmount)) {
            return this.$toast(`最多2位小数，请修改第${i+1}件的退款金额!`)
          }
          if (item.customRefundAmount > (item.remainingRefundAmount || (item.sellAmount - item.refundAmount).toFixed(2))) {
            return this.$toast(`不可大于可退金额，请修改第${i+1}件的退款金额!`)
          }
        }
        if ((this.channelId === ChannelTypeEnum.JD.value || this.channelId === ChannelTypeEnum.MT.value) && this.subCurrent === 1) {
          const isWeight = item.actualWeights.some(s => s.weight && s.weight !== '0')
          if (!isWeight) {
            return this.$toast('请输入实拣重量!')
          }
          for(let j = 0; j < item.actualWeights.length; j++) {
            const val = item.actualWeights[j]
            if (val.weight && val.weight !== '0') {
              item.weights.push(Number(val.weight))
            }
          }
        }
      }
      const goodsList = selectedArr.map(item => {
        const goodsInfo = {
          orderGoodsId: item.orderGoodsId,
          itemNumber: item.itemNumber || null,
          goodsId: item.goodsId,
          skuCode: item.skuCode,
          barcode: item.barcode,
          itemId: item.itemId || null,
          number: this.subCurrent === 0 ? item.number : null,
          actualWeights: item.weights.length ? item.weights : null,
          refundAmount: (this.subCurrent === 1 || this.subCurrent === 2) && item.customRefundAmount ? Number(item.customRefundAmount) : null
        }
        // 抖音按金额退必须传金额和重量（商品原重量）
        if (this.order.thirdChannelId === ChannelTypeEnum.DY.value) goodsInfo.actualWeights = [ item.weight ]
        return goodsInfo
      })
      const { thirdChannelId, orderId, channelOrderNo } = this.order
      const params = {
        thirdChannelId,
        orderId,
        channelOrderNo,
        partRefundType: this.subCurrent === 0 ? 1 : 3,
        goodsList,
        isRefundAll
      }
      this.$emit('confirm', params)
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper {

  .part-popup {
    padding: 20rpx;

    .tabs-line {
      height: 1rpx;
      background: #D8D8D8;
      margin-top: -10rpx;
    }

    .content-scroll {
      height: 55vh;

      .tips-box {
        padding: 18rpx 36rpx;
        border-radius: 10rpx;
        border: 2rpx solid #7dbcffff;
        background: #e6f4ffff;
        display: flex;
        align-items: center;
        margin: 24rpx auto 0;

        .icon {
          margin-right: 20rpx;
          width: 28rpx;
          height: 28rpx;
          border-radius: 50%;
          text-align: center;
          line-height: 28rpx;
          background: #0362FF;
          font-size: 20rpx;
          color: #ffffff;
        }

        .text {
          font-size: 24rpx;
          color: #000000;
        }
      }

      .goods-list {
        margin-top: 16rpx;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
        padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);

        .goods-item {
          padding: 16rpx 0;

          .item-flex {
            display: flex;

            .item-radio {
              width: 50rpx;
              position: relative;

              .checkbox {
                position: absolute;
                top: 42%;
                transform: translate(0, -50%);
              }
            }

            .image-wrap {
              width: 128rpx;
              height: 128rpx;
              position: relative;

              image {
                width: 100%;
                height: 100%;
              }
            }

            .good-info {
              flex: 1;
              margin-left: 16rpx;
              position: relative;

              .title-wrap {
                font-size: 28rpx;
                font-weight: 500;
                display: flex;
                justify-content: space-between;
                margin-bottom: 10rpx;

                .name {
                  max-width: 400rpx;
                }
              }

              .describe {
                font-size: 24rpx;
                line-height: 42rpx;
                color: #999;
                display: flex;
                align-items: center;
                justify-content: space-between;
              }

              .goods-tips {
                font-size: 24rpx;
                display: flex;
                align-items: center;
                padding: 10rpx 16rpx;
                background: #fff1f1;
                border-radius: 8rpx;
                margin-top: 10rpx;
                position: relative;
                color: #ff4141;

                .tips-icon {
                  width: 28rpx;
                  height: 28rpx;
                  border-radius: 50%;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 22rpx;
                  border: 1rpx solid #ff4141;
                }

                .tips-text {
                  line-height: 28rpx;
                  padding-left: 12rpx;
                }

                .tips-refund-text {
                  margin-left: auto;
                }

                .tips-top {
                  width: 16rpx;
                  height: 16rpx;
                  background: #fff1f1;
                  transform: rotate(45deg);
                  position: absolute;
                  z-index: 1;
                  top: -8rpx;
                  right: 12rpx;
                }
              }
            }
          }

          .stepper {
            margin-top: 20rpx;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 26rpx;

            &.mb20 {
              margin-bottom: 20rpx;
            }
          }
        }
      }
    }

    // 底部操作栏
    .footer-fixed {
      position: fixed;
      bottom: var(--window-bottom);
      left: 0;
      right: 0;
      z-index: 11;
      background: #fff;
      border-top: 2rpx solid #eee;
      // 设置ios刘海屏底部横线安全区域
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);

      .btn-wrapper {
        padding: 16rpx 32rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }

  scroll-view ::-webkit-scrollbar {
    width: 0;
    height: 0;
    background-color: transparent;
  }
}
</style>
